package com.jd.jobkeeper.server.service.db.impl;

import com.jd.jobkeeper.server.data.entity.ChangeLog;
import com.jd.jobkeeper.server.data.entity.JobInfo;
import com.jd.jobkeeper.server.data.pesistence.ChangeLogRepository;
import com.jd.jobkeeper.server.data.pesistence.JobInfoRepository;
import com.jd.jobkeeper.server.service.JobInfoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class DBJobInfoServiceImpl implements JobInfoService {

    final JobInfoRepository jobInfoRepository;
    final ChangeLogRepository changeLogRepository;

    public DBJobInfoServiceImpl(JobInfoRepository jobInfoRepository, ChangeLogRepository changeLogRepository) {
        this.jobInfoRepository = jobInfoRepository;
        this.changeLogRepository = changeLogRepository;
    }


    @Override
    public List<JobInfo> findAllByServerId(String serverId) {
        return null;
    }

    @Override
    public List<JobInfo> findAllByNamespace(String namespaceCode) {
        return jobInfoRepository.findAllByNamespaceCode(namespaceCode);
    }

    @Override
    public JobInfo getByJobId(Long id) {
        return jobInfoRepository.findById(id).get();
    }

    @Transactional
    public void update(JobInfo jobInfo) {
        jobInfo.setModifyTime(new Date());
        JobInfo r = jobInfoRepository.saveAndFlush(jobInfo);
        ChangeLog changeLog = new ChangeLog();
        changeLog.setName(JobInfo.class.getName());
        changeLog.setPk(String.valueOf(r.getId()));
        changeLog.setCreateTime(new Date());
        changeLog.setOperator(r.getNamespaceCode());
        changeLogRepository.saveAndFlush(changeLog);
    }

    @Override
    public JobInfo add(JobInfo jobInfo) {
        JobInfo r = jobInfoRepository.saveAndFlush(jobInfo);
        ChangeLog changeLog = new ChangeLog();
        changeLog.setName(JobInfo.class.getName());
        changeLog.setPk(String.valueOf(r.getId()));
        changeLog.setCreateTime(new Date());
        changeLog.setOperator(r.getNamespaceCode());
        changeLogRepository.saveAndFlush(changeLog);
        return r;
    }
}
